package com.xatime.auth.core;

import cn.hutool.json.JSONUtil;
import com.xatime.auth.core.model.User;
import lombok.AllArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;

import java.util.HashMap;
import java.util.Map;

/**
 * 解析jwt并将信息放入Authentication
 *
 * @author mason
 * @since 2018/11/14
 */
@AllArgsConstructor
public class JwtUserAuthenticationConverter extends DefaultUserAuthenticationConverter {

    private final String enhanceName;

    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {
        Object object = map.get(enhanceName);
        if (object != null) {
            User user = JSONUtil.parseFromMap((Map<?, ?>) object).toBean(User.class);
            return super.extractAuthentication(new HashMap<String, Object>(map){{put(USERNAME, user);}});
        }
        return null;
    }


}
